package com.nl.util;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.alibaba.druid.pool.DruidDataSource;

public final class ConnectionManager {

	private static final Logger logger =Logger.getLogger(ConnectionManager.class);

	private DruidDataSource dataSource = null;

	private ConnectionManager() {
		initDataSourse();
		logger.info("Initialize database connection pool.......");
	}

	private void initDataSourse() {
		dataSource = new DruidDataSource();
		dataSource.setDriverClassName(ConfigUtils.getInstance().getValue("jdbcDriverClassName"));
		dataSource.setUrl(ConfigUtils.getInstance().getValue("jdbcUrl")); 
		dataSource.setUsername(ConfigUtils.getInstance().getValue("jdbcUsername")); 
		dataSource.setPassword(ConfigUtils.getInstance().getValue("jdbcPassword"));
		dataSource.setInitialSize(Integer.parseInt(ConfigUtils.getInstance().getValue("minIdle"))); 
		dataSource.setMinIdle(Integer.parseInt(ConfigUtils.getInstance().getValue("minIdle"))); 
		dataSource.setMaxActive(Integer.parseInt(ConfigUtils.getInstance().getValue("maxActive")));
		dataSource.setMaxWait(60000);
		dataSource.setTimeBetweenEvictionRunsMillis(60000);
		dataSource.setMinEvictableIdleTimeMillis(300000);
		dataSource.setValidationQuery("select 1 from dual");
		dataSource.setTestOnBorrow(true);
		dataSource.setTestOnReturn(false);
		dataSource.setTestWhileIdle(true);
		dataSource.setPoolPreparedStatements(true);
		dataSource.setMaxPoolPreparedStatementPerConnectionSize(100);
	}

	private static class SingletonHolder {        
		private static final ConnectionManager instance = new ConnectionManager();        
	}    

	public static ConnectionManager getInstance() {
		return SingletonHolder.instance;
	}

	public synchronized Connection getConnection() throws SQLException {
		return dataSource.getConnection();
	}
}
